import { ITodoData } from "../../../typings";
import Component from "./Component";

export interface IListOptions{
    wrapperEl:HTMLElement;
    todoData: ITodoData[]
}
class List extends Component {
    private wrapperEl:HTMLElement;
    // 直接挂载到List上的静态属性
    private static todoData:ITodoData[];
    constructor(options:IListOptions){
        super();
        this.wrapperEl = options.wrapperEl;
        List.todoData = options.todoData;
    }
    public render() {
        this.wrapperEl.innerHTML += Component.listView(List.todoData);
    }
    public static addItem(val:string){
        const oTodoLis:HTMLElement = document.querySelector('.todo-list');
        const _item:ITodoData = {
            id:new Date().getTime(),
            content:val,
            complated:false
        };
        // 添加数据
        List.todoData.push(_item);
        if(List.todoData.length==1){
            oTodoLis.innerHTML = "";
        }
        // 添加一项
        oTodoLis.innerHTML += Component.todoView(_item);
    }

    public bindEvent(){
        // 利用todo-list父元素来进行事件代理
        const oTodoList:HTMLElement = document.querySelector('.todo-list');
        oTodoList.addEventListener('click',this.handleListClick.bind(this),false)
    }
    private handleListClick(e:MouseEvent){
        const target = e.target as HTMLElement, //类型断言
              targetName = target.tagName.toLowerCase();
        const oTodoItems:HTMLCollection = document.getElementsByClassName('todo-item');
        switch(targetName){
            case "input":
                this._handleCheckboxClick(target,oTodoItems);
                break;
            case "button":
                this._handleBtnClick(target,oTodoItems);
                break;
            default:
                break;
        }
    }
    private _handleCheckboxClick(tar:HTMLElement,items:HTMLCollection){
        const id:number = parseInt(tar.getAttribute('id'));
        List.todoData = List.todoData.map((todo:ITodoData,index:number) =>{
            if(todo.id === id){
                todo.complated = !todo.complated;
                items[index].querySelector('span').style.textDecoration = todo.complated?'line-through':'';
            }
            return todo;
        });
    }
    private _handleBtnClick(tar:HTMLElement,items:HTMLCollection){
        const id:number = parseInt(tar.getAttribute('data-id'));
        List.todoData = List.todoData.filter((todo:ITodoData,index:number) =>{
            if(todo.id !== id){
            return todo;
            }else{
                items[index].remove();
            }
        })
    }
}
export default List;